package com.fy.proj4_database_basic.controller;

import com.fy.proj4_database_basic.model.User;
import com.fy.proj4_database_basic.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 查询所有用户
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllUsers() {
        List<User> users = userService.findAllUsers();
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "获取用户列表成功");
        response.put("data", users);
        return ResponseEntity.ok(response);
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getUserById(@PathVariable Long id) {
        User user = userService.findUserById(id);
        Map<String, Object> response = new HashMap<>();
        
        if (user != null) {
            response.put("success", true);
            response.put("message", "获取用户成功");
            response.put("data", user);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.ok(response);
        }
    }

    // 根据用户名查询用户
    @GetMapping("/username/{username}")
    public ResponseEntity<Map<String, Object>> getUserByUsername(@PathVariable String username) {
        User user = userService.findUserByUsername(username);
        Map<String, Object> response = new HashMap<>();
        
        if (user != null) {
            response.put("success", true);
            response.put("message", "获取用户成功");
            response.put("data", user);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.ok(response);
        }
    }

    // 添加用户
    @PostMapping
    public ResponseEntity<Map<String, Object>> addUser(@RequestBody User user) {
        // 检查用户名是否已存在
        User existingUser = userService.findUserByUsername(user.getUsername());
        Map<String, Object> response = new HashMap<>();
        
        if (existingUser != null) {
            response.put("success", false);
            response.put("message", "用户名已存在");
            return ResponseEntity.ok(response);
        }
        
        User savedUser = userService.addUser(user);
        response.put("success", true);
        response.put("message", "添加用户成功");
        response.put("data", savedUser);
        return ResponseEntity.ok(response);
    }

    // 更新用户
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        User existingUser = userService.findUserById(id);
        Map<String, Object> response = new HashMap<>();
        
        if (existingUser == null) {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.ok(response);
        }
        
        // 检查用户名是否已被其他用户使用
        if (!existingUser.getUsername().equals(user.getUsername())) {
            User userWithSameUsername = userService.findUserByUsername(user.getUsername());
            if (userWithSameUsername != null) {
                response.put("success", false);
                response.put("message", "用户名已存在");
                return ResponseEntity.ok(response);
            }
        }
        
        User updatedUser = userService.updateUser(user);
        response.put("success", true);
        response.put("message", "更新用户成功");
        response.put("data", updatedUser);
        return ResponseEntity.ok(response);
    }

    // 根据ID删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteUserById(@PathVariable Long id) {
        boolean success = userService.deleteUserById(id);
        Map<String, Object> response = new HashMap<>();
        
        if (success) {
            response.put("success", true);
            response.put("message", "删除用户成功");
        } else {
            response.put("success", false);
            response.put("message", "删除用户失败，用户不存在");
        }
        return ResponseEntity.ok(response);
    }

    // 根据用户名删除用户
    @DeleteMapping("/username/{username}")
    public ResponseEntity<Map<String, Object>> deleteUserByUsername(@PathVariable String username) {
        boolean success = userService.deleteUserByUsername(username);
        Map<String, Object> response = new HashMap<>();
        
        if (success) {
            response.put("success", true);
            response.put("message", "删除用户成功");
        } else {
            response.put("success", false);
            response.put("message", "删除用户失败，用户不存在");
        }
        return ResponseEntity.ok(response);
    }

    // 分页查询用户
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> getUsersByPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        List<User> users = userService.findUsersByPage(pageNum, pageSize);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "分页获取用户成功");
        response.put("data", users);
        response.put("pageNum", pageNum);
        response.put("pageSize", pageSize);
        return ResponseEntity.ok(response);
    }
}